#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string>
#include <stdio.h>
#include <string.h>
using namespace std;

const char*  getusername()
{
    const char* name = getenv("USER");
    if(name)
        return name;
    else{
        return "none";
    }
}

const char*  gethostname()
{
    const char* name = getenv("HOSTNAME");
    if(name)
        return name;
    else{
        return "none";
    }

}

const char*  getpwd()
{
    const char* name = getenv("PWD");
    if(name)
        return name;
    else{
        return "none";
    }

}

void getcmd(char* arr, int num)
{
    cout<<"["<<getusername()<<"@"<<gethostname()<<getpwd()<<"]#";
    char* n =  fgets(arr, num, stdin);
    if(!n)
    {
        perror("fgts");
        exit(1);
    }
    arr[strlen(arr) - 1] = '\0';
}

void chartok(char* argv[], char* arr)
{
    int i = 0;
    argv[i++] = strtok(arr, " ");
    while(argv[i++]=strtok(NULL," "));
}

void testcmd(char* argv[])
{
    pid_t id = fork();
    if(id<0)
    {
        perror("fork");
        exit(-1);
    }
    else if(id == 0)
    {
        execvp(argv[0], argv);
        exit(0); 
    }
    else
    {
        pid_t rid = wait(NULL);
    }       
}

int buildcmd(char* argv[])
{
    if(!strcmp(argv[0], "cd"))
    {
        char* path = argv[2];
        if(path == NULL)
            path = ".";
        
        chdir(path); //改变当前pwd，但是文本没有改变，文本获取的是在env中获取
        
        char tmp[64] = {0};
        char cwd[1024] = {0};
        getcwd(tmp, sizeof(tmp));
        sprintf(cwd,"PWD=%s",tmp);
        putenv(cwd);

        return 1;
    }
    return 0;
}


int main()
{
    while(1)
    {
        char arr[1024]  = {0};
        char* argv[64] = {0};
        getcmd(arr , sizeof(arr));
        chartok(argv, arr);
        if(!buildcmd(argv))
             testcmd(argv);
    }
    


    return 0;
}
